package com.glory.brepda.activity.mfg;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.AddCarrierDataAdapter;
import com.glory.brepda.adapter.DefectListAdapter;
import com.glory.brepda.adapter.EDCListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.DefectCodeEntity;
import com.glory.brepda.entity.EDCListBean;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.ScrapEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.glory.brepda.utils.ShowDialog;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import org.apache.commons.lang3.StringUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: DAWorkEndActivity
 * Author: XJH
 * Date: 2020/5/21 11:02
 * Description:DA工序结束作业
 * History:
 */
public class DAWorkEndActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvTrackOutNum)
    TextView tvTrackOutNum;
    @BindView(R.id.tvEqpWork)
    TextView tvEqpWork;
    @BindView(R.id.etTrackOutNum)
    FreeUI_ClearEditText etTrackOutNum;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.tvtMatCount)
    TextView tvtMatCount;
    @BindView(R.id.etaMatCount)
    FreeUI_ClearEditText etaMatCount;
    @BindView(R.id.etProjectNum)
    FreeUI_ClearEditText etProjectNum;
    @BindView(R.id.etMaterielModel)
    FreeUI_ClearEditText etMaterielModel;
    @BindView(R.id.rvMaterielModelList)
    RecyclerView rvMaterielModelList;
    @BindView(R.id.etMaterielBox)
    FreeUI_ClearEditText etMaterielBox;
    @BindView(R.id.rvMaterielBoxList)
    RecyclerView rvMaterielBoxList;
    @BindView(R.id.rvScrapList)
    RecyclerView rvScrapList;
    @BindView(R.id.tvScrapNum)
    TextView tvScrapNum;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.tvPauseStatus)
    TextView tvPauseStatus;
    @BindView(R.id.tvSetTrackOutNum)
    TextView tvSetTrackOutNum;
    @BindView(R.id.rvEdcDataList)
    RecyclerView rvEdcDataList;
    @BindView(R.id.lotScan)
    ImageView lotScan;
    @BindView(R.id.modelScan)
    ImageView modelScan;
    @BindView(R.id.boxScan)
    ImageView boxScan;
    private static final int REQUEST_CODE_TEXT1 = 1001;
    private static final int REQUEST_CODE_TEXT2 = 1002;
    private static final int REQUEST_CODE_TEXT3 = 1003;
    private List<String> defectCodeList;
    private FreeUI_GeneralPop codePop;
    private DefectListAdapter defectListAdapter;
    private LotInfoEntity lotInfoEntity;
    private AddCarrierDataAdapter materielModelAdapter;
    private AddCarrierDataAdapter materielBoxAdapter;
    private List<String> mDurablelist;
    private String defectCode = "";
    private int subqty = 0;
    private String title;
    //批次数量
    private String mainqty;
    private EDCListAdapter edcListAdapter;
    private FreeUI_GeneralFragmentDialog scanDialog;
    private String startMainQty;
    private String matCountStandard;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_end_da;
    }

    @Override
    protected void initView() {
        title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        etLot.requestFocus();
        defectCodeList = new ArrayList<>();
        initRecyclerView(rvMaterielModelList, this);
        initRecyclerView(rvMaterielBoxList, this);
        materielModelAdapter = getCarrierAdapter();
        rvMaterielModelList.setAdapter(materielModelAdapter);
        materielBoxAdapter = getCarrierAdapter();
        rvMaterielBoxList.setAdapter(materielBoxAdapter);
        initRecyclerView(rvScrapList, this);
        defectListAdapter = new DefectListAdapter(null, tvScrapNum, false);
        defectListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        defectListAdapter.isFirstOnly(true);
        rvScrapList.setAdapter(defectListAdapter);

        edcListAdapter = new EDCListAdapter(null);
        edcListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        edcListAdapter.isFirstOnly(true);
        rvEdcDataList.setAdapter(edcListAdapter);
        initRecyclerView(rvEdcDataList, this);

        defectListAdapter.setListener(new DefectListAdapter.onListener() {
            @Override
            public void OnListener(String s, ScrapEntity item) {
                try {
                    item.setMAINQTY(s.toString());

                    item.setMAINQTY(s.toString());
                    item.setSUBQTY(s.toString());
                    ScrapEntity.MainQTY mainQTY = new ScrapEntity.MainQTY(s.toString());
                    List<ScrapEntity.MainQTY> data = new ArrayList<>();
                    data.add(mainQTY);
                    item.setQTYLIST(data);
                    long num = defectListAdapter.Calculation();
                    if (num < 0) {
                        FreeApi_ToastUtils.showFreeToast("不良数量大于批次数量，请重新输入", MyApp.app, false, Toast.LENGTH_LONG);
                        item.setMAINQTY("0");
                        item.setSUBQTY("0");
                        ScrapEntity.MainQTY mainQTY1 = new ScrapEntity.MainQTY("0");
                        List<ScrapEntity.MainQTY> data1 = new ArrayList<>();
                        data.add(mainQTY1);
                        item.setQTYLIST(data1);
                        tvScrapNum.setText("0");
                    } else {
                        tvScrapNum.setText(num + "");
                    }

                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });

        initEdit(etLot, s -> {
            LotUtils.searchLotInfo(DAWorkEndActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {

                @Override
                public void onSuccess(LotInfoEntity response) {
                    if(StringUtils.isNotEmpty(response.getTip())){
                        ShowDialog.showDialog(DAWorkEndActivity.this,response.getTip(),"制程风险提示");
                    }
                    lotInfoEntity = response;
                    tvTitle.setText("结束作业" + "(" + response.getLOT().getSTEPDESC() + ")");
                    tvLotState.setText(response.getLOT().getSTATE());
                    mainqty = response.getLOT().getMAINQTY();
                    tvTrackOutNum.setText(mainqty);
                    etTrackOutNum.setText(mainqty);
                    tvPauseStatus.setText(response.getLOT().getHOLDSTATE());
                    subqty = Integer.parseInt(response.getLOT().getMAINQTY());
                    defectListAdapter.setTotalNum(Integer.parseInt(response.getLOT().getMAINQTY()));
                    tvEqpWork.setText(response.getLOT().getEQUIPMENTID());
                    tvStep.setText(response.getLOT().getSTEPNAME() + "/" + response.getLOT().getSTEPDESC());
                    etProjectNum.setText(String.valueOf(response.getPACKAGETYPEQTY()));
                    mDurablelist = response.getDURABLELIST();
                    materielModelAdapter.setNewData(mDurablelist);
                    tvtMatCount.setText(response.getLOT().getUDF().gettMatCount());
                    etaMatCount.setText(response.getLOT().getUDF().gettMatCount());
                    startMainQty = response.getLOT().getSTARTMAINQTY();
                    matCountStandard = response.getLOT().getMATCOUNTSTANDARD();
//                    if (response.getLOT().getCOMCLASS().equals("SCHD") || response.getLOT().getCOMCLASS().equals("COM")){
//                        showConfirmDialog("批次的当前状态不允许此操作");
//                    }else {
                    getDefectInfo();
//                    }
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });

        });

        initEdit(etMaterielModel, s -> {
            if (mDurablelist == null) {
                showToast("请先扫描批次号!", false);
                return;
            }

            if (materielModelAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            materielModelAdapter.getData().add(s);
            materielModelAdapter.notifyDataSetChanged();
            etMaterielModel.setText("");
        });

        initEdit(etMaterielBox, s -> {
            if (mDurablelist == null) {
                showToast("请先扫描批次号!", false);
                return;
            }

            if (materielBoxAdapter.getData().contains(s)) {
                showToast("当前料盒已添加到列表中", false);
                return;
            }

            materielBoxAdapter.getData().add(s);
            materielBoxAdapter.notifyDataSetChanged();
            etMaterielBox.setText("");
            etMaterielBox.requestFocus();
        });
    }

    private void getDefectInfo() {

        FreeUI_EntityCallBack<BaseResponseBean<DefectCodeEntity>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<DefectCodeEntity>>
                (new TypeToken<BaseResponseBean<DefectCodeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    defectCodeList.clear();
                    List<DefectCodeEntity.DefectCode> scrapcodelists = response.body().getResponse().getBody().getADREFLIST();
                    for (DefectCodeEntity.DefectCode code : scrapcodelists) {
                        defectCodeList.add(code.getKEY() + "/" + code.getDESCRIPTION());
                        ScrapEntity scrapEntity = new ScrapEntity();
                        scrapEntity.setACTIONCODE(code.getKEY());
                        scrapEntity.setACTIONREASON(code.getDESCRIPTION());
                        scrapEntity.setLOTID(lotInfoEntity.getLOT().getLOTID());
                        scrapEntity.setLOTRRN(lotInfoEntity.getLOT().getOBJECTRRN());
                        scrapEntity.setACTIONTYPE("Scrap");
                        scrapEntity.setSUBQTY("");
//                        scrapEntity.setSUBQTY(subqty+"");
                        if (defectListAdapter.getData().size() > 0) {
                            if (containCode(scrapEntity)) {
                                defectListAdapter.addData(scrapEntity);
                            }
                        } else {
                            defectListAdapter.addData(scrapEntity);
                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "GETSTEPBYLOT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCENAME", lotInfoEntity.getSTEPLIST().get(0).getSCRAPCODESRC());
        map.addProperty("REFERENCETYPE", "USER");
        NetUtils.requestPostNet("IF.ADREFLISTQUERY", "Common", DAWorkEndActivity.this, map, callback);
    }

    @Override
    protected void initData() {

        lotScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT1);
            }
        });
        modelScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT2);
            }
        });
        boxScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT3);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && data != null) {
            String qrResult = data.getStringExtra("SCAN_RESULT"); // 获取扫码结果
            if (qrResult != null) {
                switch (requestCode) {
                    case REQUEST_CODE_TEXT1:
                        etLot.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT2:
                        etMaterielModel.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT3:
                        etMaterielBox.setText(qrResult);
                        break;
                }
            }

        }

        if (requestCode == 1) {
            finish();
        }
    }



    @OnClick({R.id.tvBaseSubmit,R.id.tvGetEDCData, R.id.tvSetTrackOutNum})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit02")) {
//                    return;
//                }
                if (getText(etLot).equals("")) {
                    showToast("请先扫描批次信息", false);
                    return;
                }

                if (tvLotState.getText().toString().equals("待投产")) {
                    showConfirmDialog("批次未投产，请联系计划部执行投产");
                    return;
                }

                if (tvLotState.getText().toString().equals("等待作业")) {
                    showConfirmDialog("批次没有作业，请操作进站功能");
                    return;
                }
                //排数出站校验：出站排数×每排标准指数≥出站数量
                Integer aMatCount = 0;
                Integer tMatCount = 0;
                if(!StringUtils.isEmpty(tvtMatCount.getText().toString())){
                    if (StringUtils.isEmpty(getText(etaMatCount))){
                        showConfirmDialog("请输入实际排数");
                        return;
                    }
                    aMatCount = Integer.parseInt(getText(etaMatCount));
                    tMatCount = Integer.parseInt(tvtMatCount.getText().toString());
                    if (StringUtils.isBlank(matCountStandard)){
                        showToast("该批次封装维护的排数数据异常",false);
                    }
                    int stadard = Integer.parseInt(matCountStandard);
                    Integer calculateMainQty = stadard*aMatCount;
                    Integer trackOutMainQty = Integer.parseInt(getText(etTrackOutNum));
                    if(calculateMainQty.compareTo(trackOutMainQty)<0){
                        showConfirmDialog("出站数量不允许大于排数计算值");
                        return;
                    }
                }

                String defectNum = tvScrapNum.getText().toString().equals("") ? "0" : tvScrapNum.getText().toString();
                String trackOutNum = etTrackOutNum.getText().toString().equals("") ? "0" : etTrackOutNum.getText().toString();
                int defect = Integer.parseInt(defectNum) + Integer.parseInt(trackOutNum);

//                if (defect != subqty) {
//                    showToast("报废数量输入不正确", false);
//                    return;
//                }

                List<String> data = materielModelAdapter.getData();

                List<String> dataBox = materielBoxAdapter.getData();
                data.addAll(dataBox);

                Bundle bundle = new Bundle();
                bundle.putString("LOTID",getText(etLot));
                bundle.putString("EQPID",tvEqpWork.getText().toString());
                bundle.putString("DEFECTCODE",defectNum);
                bundle.putString("SCRAPCODESRC",tvScrapNum.getText().toString().equals("")?"0":tvScrapNum.getText().toString());
                bundle.putString("TRACKOUTNUM",etTrackOutNum.getText().toString());
                bundle.putString("method","DBLOTTRACKOUT");
                bundle.putString("scan",tvTrackOutNum.getText().toString());
                bundle.putSerializable("LOTINFOENTITY", lotInfoEntity);
                bundle.putSerializable("ScrapList", (Serializable)defectListAdapter.getData());
                bundle.putString("title", title);
                bundle.putString("aMatCount", getText(etaMatCount));//实际排数
                bundle.putString("tMatCount", tvtMatCount.getText().toString());//实际排数
                bundle.putStringArrayList("MATERIELMODELLIST", (ArrayList<String>) data);
                Intent intent = new Intent(this, WBWorkEnd2Activity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent,1);
                break;
            case R.id.tvSetTrackOutNum:
                scanDialog = FreeApi_DialogUtils.getScanDialog(this, "请输入出站数量", new FreeUI_TextCallback() {
                    @Override
                    public void onSuccess(String s) {
                        try {
                            int inputMainQty = Integer.parseInt(s);
                            int mainQty = Integer.parseInt(mainqty);
                            if (inputMainQty < mainQty) {
                                showToast("出站数量不能调小", false);
                                return;
                            }

                            tvTrackOutNum.setText(s);
                            scanDialog.dismiss();
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            showToast("请输入数字", false);
                        }

                    }
                });
                scanDialog.show(getSupportFragmentManager(), "SET_TEACKOUT_NUM");
                break;
            case R.id.tvGetEDCData:
                FreeUI_EntityCallBack<BaseResponseBean<EDCListBean>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EDCListBean>>
                        (new TypeToken<BaseResponseBean<EDCListBean>>() {
                        }.getType(),getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<EDCListBean>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(DAWorkEndActivity.this, false, getSupportFragmentManager())) {
                            edcListAdapter.setNewData(response.body().getResponse().getBody().getList());
                            for(EDCListBean.ListBean edcList:response.body().getResponse().getBody().getList()){
                                for(ScrapEntity defectList: defectListAdapter.getData()){
                                    if (edcList.getName().equals(defectList.getACTIONCODE())){
                                        defectList.setMAINQTY(edcList.getValue());
                                    }
                                }
                            }
                            defectListAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<EDCListBean>> response) {
                        super.onError(response);
                        FreeApi_LogUtils.saveErrorMessages(response.getException(), "TrackOutEDC");
                        FreeApi_ToastUtils.showFreeToast("连接服务器失败", DAWorkEndActivity.this, false, 0);
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("EQUIPMENTID", tvEqpWork.getText().toString());
                map.addProperty("LOTID", getText(etLot));
                NetUtils.requestPostNet("TrackOutEDC", "TrackOutEDC", DAWorkEndActivity.this, map, callBack);
                break;
        }

    }

    private boolean containCode(ScrapEntity scrapEntity) {
        for (ScrapEntity bean : defectListAdapter.getData()) {
            if (bean.getACTIONCODE().equals(scrapEntity.getACTIONCODE())) {
                showToast("列表中已有当前不良代码!", false);
                return false;
            }
        }
        return true;
    }

    private long Calculation() {
        long sum = 0;
        List<ScrapEntity> data = defectListAdapter.getData();

        if (data.size() <= 0) {
            return 0;
        }


        for (ScrapEntity entity : data) {
            sum += Integer.parseInt(entity.getSUBQTY().equals("") ? "0" : entity.getSUBQTY());
        }


        if (sum > Integer.parseInt(lotInfoEntity.getLOT().getMAINQTY())) {
            sum = -1;
        }

        return sum;
    }


    void getEdcData(){
        FreeUI_EntityCallBack<BaseResponseBean<EDCListBean>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EDCListBean>>
                (new TypeToken<BaseResponseBean<EDCListBean>>() {
                }.getType(),getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EDCListBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(DAWorkEndActivity.this, false, getSupportFragmentManager())) {
                    edcListAdapter.setNewData(response.body().getResponse().getBody().getList());
                    for(EDCListBean.ListBean edcList:response.body().getResponse().getBody().getList()){
                        for(ScrapEntity defectList: defectListAdapter.getData()){
                            if (edcList.getName().equals(defectList.getACTIONCODE())){
                                defectList.setMAINQTY(edcList.getValue());
                            }
                        }
                    }
                    defectListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EDCListBean>> response) {
                super.onError(response);
                FreeApi_LogUtils.saveErrorMessages(response.getException(), "TrackOutEDC");
                FreeApi_ToastUtils.showFreeToast("连接服务器失败", DAWorkEndActivity.this, false, 0);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID", tvEqpWork.getText().toString());
        map.addProperty("LOTID", getText(etLot));
        NetUtils.requestPostNet("TrackOutEDC", "TrackOutEDC", DAWorkEndActivity.this, map, callBack);

    }
}